## 

rm(list = ls())

## 

library(rdrobust)
library(tidyverse)
library(pbapply)

## Declare covars

covs <- c('turnout_party_2009_btw', 'soz_vers_beschaeftigte_share',
          'pop_density_km2', 'migration_out_share')

## Get municipal election data

mu <- read_rds("data/data_municipal.rds") %>%
  filter(!is.na(treated)) %>%
  mutate(state_id = substr(ags, 1, 2))

## Drop period t-2 (i.e. we only want two periods)

mu <- mu %>% 
  filter(time_rel_period > -2)

## Declare outcomes to use

outcomes <- c('agg_left', 'agg_right', 'agg_center',
              'cdu_csu', 'turnout', 'spd',
              'fdp', 'greens', 'left',
              'other_party', 
              'left_total',
              'right_total',
              'incumbent_share')

## Source helper function to tidy rdrobust output

source("code/tidy_rd.R")

## Convert to first differences

diff_df <- pblapply(outcomes, function(o) {
  out <- mu %>%
    filter(time_rel_period > -2) %>%
    mutate(time_rel_period = time_rel_period + 2)  %>% 
    pivot_wider(values_from = o, names_from = 'time_rel_period', 
                id_cols = 'ags',
                names_prefix = 'o') %>%
    mutate(diff = o2  - o1) %>%  dplyr::select(ags, diff) 
  ## Rename
  colnames(out)[2] <- o
  
  ## Return this
  out
}) %>%
  reduce(left_join) %>%
  left_join(mu %>% dplyr::select(ags, pop_dec_09, applies_census,
                                 one_of(covs), state_id) %>%
              distinct(ags, .keep_all = T)) %>%
  mutate(runvar = (pop_dec_09 * -1) + 10000) %>%
  filter(applies_census == 1)

## Estimate
## This loops over outcomes

out_rd_opt <- pblapply(outcomes, function(o) {
  
  ## Iterate over whether or not to exclude B-W
  
  lapply(c(T,F), function(exclude_state) {
    
    if (exclude_state) {
      subset_select <- !diff_df$state_id == '08' 
    } else {
      subset_select <- rep(T, nrow(diff_df))
    }
    
    out <- rdrobust(y = diff_df[subset_select, o] %>% pull(!!o), 
                    x = diff_df$runvar[subset_select], c = 0,
                    covs = diff_df[subset_select, covs])
    
    ## Tidy and return
    
    out2 <- out %>% 
      tidy_rd(se_nr = 3) %>% 
      mutate(outcome = o, 
             exclude_state = ifelse(exclude_state, 
                                    'State excluded', 'All states')) %>% 
      dplyr::rename(se = std.error, pval = p.value, 
                    bw = bw_left_h,
                    bw_bias = bw_left_b) %>% 
      mutate(conf.low90 = estimate - qnorm(0.95)*se,
             conf.high90 = estimate + qnorm(0.95)*se)
    
    ## Return
    
    out2
  }) %>% reduce(rbind)
}) %>%
  reduce(rbind)

## Save this

write_rds(out_rd_opt, 'data/rdd_municipal_results.rds')
